//
//  WDForgetController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/29.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDForgetController.h"
#import "WDResetController.h"
#import "WDForgetMessage.h"
#import "UIViewController+WDShowAlertController.h"

@interface WDForgetController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNumText;
@property (weak, nonatomic) IBOutlet UITextField *securityKeyText;
@property (weak, nonatomic) IBOutlet UIButton *securityKeyBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (assign, nonatomic, getter=isPhoneNumber) BOOL phoneNumber;
@property (assign, nonatomic, getter=isStartTimer) BOOL startTimer;
/** 请求返回信息 */
@property (nonatomic, strong) WDForgetMessage *message;


@end

@implementation WDForgetController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加载导航条
    [self loadNavItemWithAction:@selector(clickNavLeftBtn) btnImage:@"icon_back" btnSelImage:@"icon_back" title:@"重置密码"];
    
    //加载验证码按钮
    [self setUpSecurityKeyBtn];
    
    [self setUpNextBtn];
    
    //监听手机号是否到11位
    [self.phoneNumText addTarget:self action:@selector(phoneNumChange) forControlEvents:UIControlEventEditingChanged];
    
    //监听验证码是否输入
    [self.securityKeyText addTarget:self action:@selector(securityKeyChange) forControlEvents:UIControlEventEditingChanged];
    
    
}

#pragma mark - 监听文本框输入
- (void)phoneNumChange
{
    if (self.phoneNumText.text.length >= 11) {//如果手机号输入11位，验证码按钮可点击
        
        if (self.isStartTimer) {
            self.securityKeyBtn.enabled = NO;
            self.securityKeyBtn.backgroundColor = [UIColor grayColor];
        } else {
            self.securityKeyBtn.enabled = YES;
            self.securityKeyBtn.backgroundColor = WDNavSeleColor;
        }
        
    } else {
        self.securityKeyBtn.enabled = NO;
        self.securityKeyBtn.backgroundColor = [UIColor grayColor];
    }
    
    if (self.phoneNumText.text.length >= 11 && self.securityKeyText.text.length >= 4) {
        
        self.nextBtn.enabled = YES;
        self.nextBtn.backgroundColor = WDNavSeleColor;
        
    } else {
        
        self.nextBtn.enabled = NO;
        self.nextBtn.backgroundColor = [UIColor grayColor];
    }
}

/** 监听验证码的长度 */
- (void)securityKeyChange
{
    if (self.phoneNumText.text.length ==11 && self.securityKeyText.text.length == 4) {//手机号11位并且验证码4位，则可点击下一步
        self.nextBtn.enabled = YES;
        self.nextBtn.backgroundColor = WDNavSeleColor;
    } else {
        self.nextBtn.enabled = NO;
        self.nextBtn.backgroundColor = [UIColor grayColor];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self preferredStatusBarStyle];
    
    //显示导航条
    self.navigationController.navigationBar.hidden = NO;
    
}

//设置StatusBar样式
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - 点击事件
- (IBAction)getSecurityKeyBtn {
    
    //发请求，验证手机号
    [self postRequestPhone];
}

- (IBAction)clickNextBtn {
    
    [self.view endEditing:YES];
    
    //判断验证码是否正确
    [self requestPostSecurty];
    
}

- (void)clickNavLeftBtn
{
    [self.view endEditing:YES];
    
    //弹出提示是否放弃修改密码
    [self creatAlert];
    
}

#pragma mark - 发网络请求
- (void)postRequestPhone
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSDictionary *parameters = @{
                                 @"phone":self.phoneNumText.text,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFindPwd];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.message = [WDForgetMessage mj_objectWithKeyValues:responseObject];
        
        if(self.message.error_code == 0)//手机号有效
        {
            self.phoneNumber = YES;
            
            //验证手机号
            if(self.isPhoneNumber) {//手机号能收到短信
                
                //开始计时，计时期间不能点击
                __block int timeout = WDSecurityTime; //倒计时时间
                
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                
                dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                
                dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                
                dispatch_source_set_event_handler(_timer, ^{
                    
                    if(timeout <= 0){ //倒计时结束，关闭
                        
                        dispatch_source_cancel(_timer);
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //设置界面的按钮显示
                            [self.securityKeyBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                            
                            self.securityKeyBtn.userInteractionEnabled = YES;
                            
                            self.startTimer = NO;
                            
                            self.securityKeyBtn.backgroundColor = WDNavSeleColor;
                        });
                    } else {
                        self.startTimer = YES;
                        
                        int seconds = timeout;
                        
                        NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            //让按钮变为不可点击的灰色
                            self.securityKeyBtn.backgroundColor = [UIColor grayColor];
                            
                            self.securityKeyBtn.userInteractionEnabled = NO;
                            
                            //设置界面的按钮显示
                            [UIView beginAnimations:nil context:nil];
                            
                            [UIView setAnimationDuration:1];
                            
                            [self.securityKeyBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                            
                            [UIView commitAnimations];
                        });
                        
                        timeout--;
                    }
                });
                
                dispatch_resume(_timer);
                
            }
            
        } else {
            
            self.phoneNumber = NO;
            
            [self showAlertWithMessage:self.message.error_msg];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@",error);
        
    }];
}

- (void)requestPostSecurty
{
    NSDictionary *parameters = @{
                                 @"phone":self.phoneNumText.text,
                                 @"verify_code":self.securityKeyText.text,
                                 @"ctype":@3
                                 };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLValiData];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.message = [WDForgetMessage mj_objectWithKeyValues:responseObject];
        
        if (self.message.error_code == 0) {
            //都正确就跳转控制器
            WDResetController *tempVC = [[WDResetController alloc] init];
            tempVC.uid = self.message.uid;
            
            tempVC.view.backgroundColor = [UIColor whiteColor];
            
            [self.navigationController pushViewController:tempVC animated:YES];
            
        } else {
            
            [self showAlertWithMessage:self.message.error_msg];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@",error);
        
    }];
}

#pragma mark - 自定义加载控件
/** 设置验证码按钮 */
- (void)setUpSecurityKeyBtn
{
    //设置验证码按钮
    self.securityKeyBtn.backgroundColor = [UIColor grayColor];
    
    [self.securityKeyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    
    self.securityKeyBtn.layer.cornerRadius = 5;
    
    self.securityKeyBtn.layer.masksToBounds = YES;
}

/** 设置下一步按钮 */
- (void)setUpNextBtn
{
    self.nextBtn.backgroundColor = [UIColor grayColor];
    self.nextBtn.layer.cornerRadius = 2;
    self.nextBtn.clipsToBounds = YES;
}

/** 弹出提示框 */
- (void)creatAlert
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"你是否要放弃重置密码" preferredStyle:UIAlertControllerStyleAlert];
    
    //确定
    UIAlertAction *certain  = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        //返回上一页
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    //取消
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:certain];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - <UITextFiledDelegate>
//限制输入位数
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    NSInteger existedLength = textField.text.length;
    
    NSInteger selectedLength = range.length;
    
    NSInteger replaceLength = string.length;
    
    if(textField.tag == 11) {//输入的是手机号
        
        if (string.length == 0) return YES;
        
        if (existedLength - selectedLength + replaceLength > 11) {
            
            return NO;
        }
        
    } else {//输入的是验证码
        
        if (string.length == 0) return YES;
        
        if (existedLength - selectedLength + replaceLength > 4) {
            
            return NO;
        }
    }
    return YES;
}

@end
